package m2runtime

import (
	"runtime"
	"fmt"
	"time"
)

// 1. 让出CPU时间片，gosched
func RuntimeDemo1()  {
	// 1. 定义协程匿名函数打印2次hello
	// 2. 定义主线程打印2次world
	go func(s string) {
		for i := 0; i < 2; i++ {
			println(s, "=", i)
		}
	}("hello")

	for i := 0; i < 2; i++ {
		runtime.Gosched()
		println("world=", i)
	}
}

// 2. 退出当前协程
func RuntimeDemo2()  {
	go func() {
		defer fmt.Println("A.defer")
		func() {
			defer fmt.Println("B.defer")
			// 结束协程
			runtime.Goexit()
			defer fmt.Println("C.defer")
			fmt.Println("B")
		}()
		fmt.Println("A")
	}()
	// 祝线程
	time.Sleep(10 * time.Second)
}

// 3. m2runtime.GOMAXPROCS设置并发占用的当前核心数
func A()  {
	for i := 0; i < 10; i++ {
	 	println("A-", i)
	}
}

func B()  {
	for i := 0; i < 10; i++ {
	    println("B-", i)
	}
}


func RuntimeDemo3()  {

	runtime.GOMAXPROCS(2)

	go A()

	go B()

	time.Sleep(time.Second)

}